package org.grupoavatar.guiaubicua.controller;

import java.io.IOException;
import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.util.EntityUtils;
import org.grupoavatar.guiaubicua.auxiliares.Utiles;
import org.grupoavatar.guiaubicua.entities.POIBean;
import org.grupoavatar.guiaubicua.framework.Controller;
import org.grupoavatar.guiaubicua.framework.HttpConnector;
import org.grupoavatar.guiaubicua.model.GetListaPOIs;

import android.content.Context;
import android.graphics.drawable.Drawable;

import com.google.gson.Gson;

public class POIController extends Controller {
	public static POIController instance = null;
	private static ArrayList<POIBean> listaPOI = null;
	
	public static POIController getInstance() {
		if (instance == null) {
			instance = new POIController();
		}
		return instance;
	}
	
	public ArrayList<POIBean> getPOIs() {
		String path = Utiles.getPuntosURL();
//		String path = "http://localhost:8080/dp2/api/" + ServerConstants.COSTOS_CO_GETLISTAINDICADORES_URL + "/";
		
		Gson gs = new Gson();
		String strResponse = "";
		GetListaPOIs objResponse = null;

		
		//strResponse = "{\"lista\":[{\"nombre\":\"PV\",\"valor\":\"4016\"},{\"nombre\":\"EV\",\"valor\":\"4016\"},{\"nombre\":\"AC\",\"valor\":\"3808\"},{\"nombre\":\"CV\",\"valor\":\"208\"},{\"nombre\":\"CPI\",\"valor\":\"1.0546218487395\"},{\"nombre\":\"SPI\",\"valor\":\"1\"},{\"nombre\":\"SV\",\"valor\":\"0\"}]}";
		//strResponse = getStringFromPOST(path, null);
		//deberia usarse metodo GET
		
		HttpResponse respuesta = HttpConnector.makeGetRequest(path, "");
		String result;
		if ((respuesta != null) && respuesta.getStatusLine().getStatusCode() == 200) {
			try {
				result = EntityUtils.toString(respuesta.getEntity());
				objResponse = gs.fromJson(result, GetListaPOIs.class);
//				if (objResponse.indicadores == null) {
//					mensaje = gs.fromJson(result, GetMensaje.class);
//				}
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				result = strResponse;
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				result = strResponse;
			}
		} else {
			result = strResponse;
		}
		
		//objResponse = gs.fromJson(result, GetListaIndicadoresResponse.class); //temporalmente para pruebas, luego se debe borrar esta linea.
		if (objResponse!=null){
			listaPOI = objResponse.listaPOIs;
		} else {
			listaPOI = null;
			
		}
		return listaPOI;
	}
	
	public ArrayList<POIBean> getLocalPOIs() {
		return listaPOI;
	}
	
	public Drawable getIconoDrawable(Context c, POIBean poi) {
		return c.getResources().getDrawable(poi.getIcono());
	}
}
